package org.eenie.appseed.ui.crash

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.recyclical.datasource.dataSourceOf
import com.afollestad.recyclical.setup
import com.afollestad.recyclical.withItem
import com.blankj.utilcode.util.TimeUtils
import org.eenie.appseed.R
import org.eenie.appseed.databinding.ActivityCrashBinding
import org.eenie.appseed.databinding.ItemLogFileLayoutBinding
import org.eenie.appseed.ui.main.BindingViewHolder
import org.eenie.core.base.viewbinding.BaseBindingActivity
import xcrash.TombstoneManager
import xcrash.XCrash
import java.io.File
import java.util.Date

open class CrashActivity : BaseBindingActivity<ActivityCrashBinding>() {


    override fun initUI() {
        val data = dataSourceOf()
        data.addAll(TombstoneManager.getAllTombstones().apply {
            sortDescending()
        }.toMutableList())

        this.binding.rvLog.addItemDecoration(DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL))

        this.binding.rvLog.setup {
            this.withLayoutManager(LinearLayoutManager(mContext))
            withDataSource(dataSource = data)

            withItem<File, BindingViewHolder>(R.layout.item_log_file_layout) {
                onBind(::BindingViewHolder) { index, item ->
                    val binding = binding<ItemLogFileLayoutBinding>()
                    binding.tvTime.text = "${index + 1}·崩溃时间：" + TimeUtils.date2String(Date(item.lastModified()), "yyyy-MM-dd HH:mm:ss")
                    binding.tvFile.text = item.name
                }

                onClick { index ->
                    val file = data[index] as File
                    startActivity(Intent(mContext, LogPreviewActivity::class.java).putExtra("path", file.absolutePath))
                }


            }

        }

    }

    public fun testJavaCrash(view: View) {
        XCrash.testJavaCrash(false)
    }

    public fun testNativeCrash(view: View) {
        XCrash.testNativeCrash(false)
    }

    override fun providerBinding() = ActivityCrashBinding.inflate(layoutInflater)


}